<?php
	if( !isset($_COOKIE["username"]) ){
		header("Location:login.php");
	}else{
		setcookie("username", $_COOKIE["username"],time() + 900);
	}
	include_once 'json_function.php';
	$ini_array = parse_ini_file("config/config.ini");
	
	$conn = @mysqli_connect($ini_array["host"], $ini_array["username"], $ini_array["password"], $ini_array["db_name"]) or die("cann't connect the mysql db");
	mysqli_set_charset($conn, "utf8");
	ini_set('default_charset', "UTF-8");
	$procedureNo = mysqli_real_escape_string($conn,$_POST["procedureNo"]);
	$procedureDescription = mysqli_real_escape_string($conn,$_POST["procedureDescription"]);
	
	$operateSql;
	$operateType;
	
	if( $procedureNo == 0 ){
		$operateSql = "insert into procedurelist(procedure_description)values('".$procedureDescription."')";
		$operateType = "Add";
	}else{
		$isExistSql = "select count(procedure_no) count from procedurelist where procedure_no=".$procedureNo;
		$isExistResult = mysqli_query($conn, $isExistSql);
		$row = mysqli_fetch_array($isExistResult);
		$count = $row["count"];
		if( $count == 0 ){
			$operateSql = "insert into procedurelist(procedure_description)values('".$procedureDescription."')";
			$operateType = "Add";
		}else{
			$operateSql = "update procedurelist set procedure_description='".$procedureDescription."' where procedure_no=".$procedureNo;
			$operateType = "Update";
		}
	}
	
	$operateResult = mysqli_query($conn, $operateSql);
	
	if( $procedureNo == 0 ){
		$procedureNo = mysqli_insert_id($conn);
	}
	$data = "{\"data\":{";
	if( $operateResult ){
		$data .= "\"status\":\"success\", \"msg\":\"".$operateType." success!!!\", \"procedureNo\":\"".$procedureNo."\"}}";
	}else{
		$data .= "\"status\":\"fail\",\"msg\":\"".$operateType." fail!!!".mysqli_error($conn)."\"}}";
	}
	echo JsonCharFilter($data);
?>